package jwt

import (
	"encoding/base64"
	"encoding/json"
	"errors"
	"strings"
)

var algorithms = map[string]IAlgorithm{
	"HS256": HS256,
}

func GetAlgorithm(id string) IAlgorithm {
	return algorithms[id]
}

func Token(data, secret string, algorithm IAlgorithm) (token string, err error) {
	return NewGenerator(secret, algorithm).TokenByString(data)
}

func Verify(token, secret string, payload IPayload) (err error) {
	var parts []string
	if parts, err = splitToken(token); nil != err {
		return
	}

	var headerBuf []byte
	if headerBuf, err = base64.RawURLEncoding.DecodeString(parts[0]); nil != err {
		return
	}

	header := NewDefaultHeader()
	if err = json.Unmarshal(headerBuf, header); nil != err {
		return
	}

	err = NewValidator(secret, GetAlgorithm(header.GetAlgorithm())).
		SetHeaderPart(parts[0]).
		SetPayloadPart(parts[1]).
		SetSignPart(parts[2]).
		Verify(payload)

	return
}

func splitToken(token string) (parts []string, err error) {
	parts = strings.Split(token, ".")
	if 3 != len(parts) {
		err = errors.New("invalid token format")
	}

	return
}
